#include "Texture.h"
#include "NeroEngine\NPlatform.h"
#include "NeroCore\NMemoryManager.h"

using namespace Graphics;

#ifdef DX_11
#include <d3dx11tex.h>
#endif

RTTI_DEFINITIONS(Texture)

Texture::Texture(void)
	:NResource(),
	 mTexture(NULL)
{
}

Texture::Texture(const std::string& instanceName, ID3D11ShaderResourceView* texture)
	:NResource(instanceName,""),
	 mTexture(texture)
{
	mIsInitialized = true;
}

Texture::Texture(const std::string& instanceName, const std::string& filePath)
	:NResource(instanceName, filePath),
	 mTexture(NULL)
{
}

Texture::~Texture(void)
{
	Deinitialize();
}

bool Texture::Initialize()
{
	HRESULT result;
	if(GetPlatform()->GetDevice() && !mIsInitialized)
	{
#ifdef DX_9
		Engine::NPlatform* platform = GetPlatform();
		D3DDevice* device = platform->GetDevice()->As<D3DDevice>();
		result = D3DXCreateTextureFromFile( device->GetDevice(), mFilePath.c_str(), &mTexture);
#elif defined(DX_11)
		D3DDevice* device = GetPlatform()->GetDevice()->As<D3DDevice>();
		result = D3DX11CreateShaderResourceViewFromFile(device->GetDevice(), mFilePath.c_str(), NULL, NULL, &mTexture, NULL);
		mTexture->SetPrivateData(WKPDID_D3DDebugObjectName, this->GetFileName().length(), this->GetFileName().c_str());
#endif
		mIsInitialized = true;
		CHECK(result)
		return true;
	}	
	return false;
}

void Texture::Deinitialize()
{
	if(mTexture)
	{
		mTexture->Release();
		mTexture = NULL;
	}
}

#ifdef DX_9
LPDIRECT3DTEXTURE9 Texture::GetResource()
{
	return mTexture;
}
#elif defined(DX_11)
ID3D11ShaderResourceView* Texture::GetResource()
{
	return mTexture;
}
#endif

#ifdef DX_11
TextureArray::TextureArray()
	:mTextures(NULL)
{
}

TextureArray::~TextureArray()
{
}

Texture* TextureArray::operator[](unsigned int index)
{
	return mTextures[index];
}

bool TextureArray::Initialize(int size)
{
	return true;
}

void TextureArray::Deinitialize()
{
	mTextures.clear();
}

std::vector<Texture*>& TextureArray::GetTextures()
{
	return mTextures;
}

bool TextureArray::AddTexture(const char* textureName)
{
	Texture* texture = MY_NEW(Memory::HID_Rendering,"Texture") Texture("", textureName);

	texture->Initialize();

	mTextures.push_back(texture);
	return true;
}

bool TextureArray::AddTexture(Texture* texture)
{
	texture->Initialize();

	//do some checks
	mTextures.push_back(texture);

	return true;
}
#endif